/**
 参看：Ionic4 Cordova 调用原生硬件 Api 实现扫码功能
 地址： https://my.oschina.net/u/4279402/blog/3435245
 第一步：安装插件
 ionic cordova plugin add cordova-plugin-qrscanner
 npm install @ionic-native/qr-scanner

 第二步：在文件 app.module.ts 中引入依赖注入
 import { QRScanner } from '@ionic-native/qr-scanner/ngx';
 ......
 providers: [
 Camera,
 　　......,
 　　QRScanner,
 { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
 ]

 第三步：新建页面
 ionic g page scan

 第四步：使用
 下载扫码框背景图 scanner.svg 放在 src/assets 目录里面
 下载地址:http://www.ionic.wang/scanner_svg.zip

 */


import {Component, EventEmitter, OnInit, Output} from '@angular/core';

import {QRScanner, QRScannerStatus} from '@ionic-native/qr-scanner/ngx';

import {NavController} from '@ionic/angular';
import {EventService} from '../../wzqService/event.service';


@Component({
  selector: 'app-scan',
  templateUrl: './scan.page.html',
  styleUrls: ['./scan.page.scss'],
})
export class ScanPage implements OnInit {

  public light: boolean; // 判断闪光灯
  public frontCamera: boolean; // 判断摄像头
  public isShow: boolean = false; // 控制显示背景，避免切换页面卡顿

  /****************************************************************/
  public receivedData; // 接收到的数据（来自url）
  public scanText = null; // 扫码识别到的数据


  constructor(
    private qrScanner: QRScanner,
    public navController: NavController,
    public eventService: EventService,
  ) {
    // 下面格式化必须要有
    const sendDataToScanPage = localStorage.getItem('sendDataToScanPage');
    if (sendDataToScanPage) {
      this.receivedData = JSON.parse(JSON.stringify(sendDataToScanPage));
    } else {
      this.receivedData = null;
    }
  }

  ngOnInit() {
    // this.ionViewWillEnter() ;
  }

  // 刚进来的时候执行扫码
  ionViewWillEnter() {

    this.qrScanner.prepare()
      .then((status: QRScannerStatus) => {
        if (status.authorized) {
          // start scanning
          let scanSub = this.qrScanner.scan().subscribe((text: string) => {
            // console.log('Scanned something', text);
            // alert(text);
            this.scanText = text;
            this.qrScanner.hide(); // hide camera preview
            scanSub.unsubscribe(); // stop scanning
            this.navController.back();
          });
          // 打开摄像头
          this.qrScanner.show();
        } else if (status.denied) {
          // console.log('没有摄像头权限，请前往设置中开启');
          alert('没有摄像头权限，请前往设置中开启');
        } else {
          // permission was denied, but not permanently. You can ask for permission
          // console.log('没有摄像头权限，请前往设置中开启');
          alert('没有摄像头权限，请前往设置中开启');
        }
      })
      .catch((e: any) => {
        // console.log('Error is', e);
        alert('Error is ' + JSON.stringify(e));
      });
  }

  ionViewDidLeave() {
    // 扫码页面返回的时候发送广播
    this.eventService.eventEmit.emit('scanPageCloseEvent', this.scanText);
  }


  /*页面可见后执行 */
  ionViewDidEnter() {
    this.isShow = true; // 显示背景
    // console.log('ionViewDidEnter');
  }


  /**
   * 闪光灯控制，默认关闭
   */
  toggleLight() {
    if (this.light) {
      this.qrScanner.disableLight();
    } else {
      this.qrScanner.enableLight();
    }
    this.light = !this.light;
  }

  /**
   * 前后摄像头互换
   */
  toggleCamera() {
    if (this.frontCamera) {
      this.qrScanner.useBackCamera();
    } else {
      this.qrScanner.useFrontCamera();
    }
    this.frontCamera = !this.frontCamera;
  }

  //组件销毁
  ionViewWillLeave() {
    this.qrScanner.hide(); // 需要关闭扫描，否则相机一直开着
    this.qrScanner.destroy(); // 关闭
  }

}
